package com.kgc.sbt.controller;

import javax.servlet.http.HttpServletRequest;

/**
 * Created on 2021/8/10.
 * <p>
 * Author: wuqilong
 * <p>
 * Description: 所有控制器的父类，提供一些公共方法
 */
public class BaseController {

    /**
     * @author : 武
     * @date : 2021/8/10
     * @return :
     * @description : 从request中获取参数，如果没有，默认为空字符串
     */
    protected String getParameter(HttpServletRequest request, String key){
        return request.getParameter(key) == null ? "" : request.getParameter(key);
    }

    /**
     * @author : 武
     * @date : 2021/8/10
     * @return :
     * @description : 从request中获取参数，如果没有，指定默认值
     */
    protected String getParameterUseDefValue(HttpServletRequest request, String key, String defaultValue){
        return request.getParameter(key) == null ? defaultValue : request.getParameter(key);
    }

    /**
     * @author : 武
     * @date : 2021/8/10
     * @return : java.lang.String
     * @description : 获取请求的来源ip
     */
    protected String getRemoteIp(HttpServletRequest request) {
        // 获取ip
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
}
